package fu.capstone.hanoicityguide.common.utility;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.DownloadManager;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class CacheCommonDialogues {

	public CacheCommonDialogues() {
	}

	public File getCacheFolder(Context context) {
		File cacheDir = null;
		
		// media_mounted = having sdcard, if not, get the internal memory
		if ((Environment.getExternalStorageState()
				.equals(Environment.MEDIA_MOUNTED))) {
			cacheDir = new File(Environment.getExternalStorageDirectory() + "/"
					+ "Android" + "/" + "data" + "/"
					+ "fu.capstone.hanoicityguide", "Dialogues Cache");

			if (!cacheDir.isDirectory()) {
				cacheDir.mkdir();
			}
		}
		
		if (!cacheDir.isDirectory()) {
			cacheDir.mkdir();
		}
		
		return cacheDir;
	}
	
	/*This method will do 2 things
	 * 1. Get the file from URL
	 * 2. Write that file into cache folder create above*/
	
	public void writeFiletoCache(Context context, String fileURL, int id) {
	
		DownloadManager mgr = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);
		
		
		File file = new File(Environment.getExternalStorageDirectory() + 
				"/Android/data/fu.capstone.hanoicityguide/files/audio"
						+ id);
		
		if (file.exists()) {
			// Do somehting
			Log.v("Download file", "File" + id + " is already downloaded");
		} else {
			// Do something else.
			Uri source = Uri.parse(fileURL);
			// Uri destination = Uri.fromFile(new File(“local file path”));

			DownloadManager.Request request = new DownloadManager.Request(source);
			request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
					| DownloadManager.Request.NETWORK_MOBILE);
			request.setVisibleInDownloadsUi(false);
			request.setDestinationInExternalFilesDir(
					context.getApplicationContext(), null, "audio" + id);
//			 request.setNotificationVisibility(DownloadManager
//			 .Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
			request.allowScanningByMediaScanner();

			mgr.enqueue(request);

		}
	
	}
	
	
	public static File[] getListFile(Context context) {
		File[] list = null;
		
		if (Environment.MEDIA_MOUNTED.equals("mounted")) {
			// We can read and write the media
//			Log.v("Get list file", 
//					"Media Mounted status: true" );
			try {
				File mfile = new File(Environment.getExternalStorageDirectory() + 
						"/Android/data/fu.capstone.hanoicityguide/files/");
				list = mfile.listFiles();
				if (list.length == 0)
					Log.v("Get list file", "Folder is empty");
				else {
//					for (int i = 0; i < list.length; i++)
//						Log.v("Get list file", list[i].toString());
				}
			} catch (Exception e) {
				Log.v("Get list file", 
						e.toString() );
			}

		} 
		else {
			Toast.makeText(context,
					"Media Mounted status: Error occured", Toast.LENGTH_LONG).show();
		}
		
		return list;
	}
	
	
	
	public void startPlaying(Context context , String fileName) {
//	  	// File fFile = new File(context.getExternalCacheDir() + "/" +
		// fileName);
		File fFile = new File(Environment.getExternalStorageDirectory() + 
				"/Android/data/fu.capstone.hanoicityguide/files/"
						+ fileName);
//		fFile.setReadable(true, false);
		if (!fFile.isFile()) {
			Toast.makeText(context, "File not found! Please turn on internet connection to redownload!", Toast.LENGTH_SHORT)
					.show();
		} else {
			try {
				FileInputStream fisAudio = new FileInputStream(fFile);
				// fmpAudio.setDataSource(VocaPreview.this.getCacheDir() + "/" +
				// asAudioFileName.toLowerCase() + ".mp3");
				// fmpAudio.setDataSource("/sdcard/2.mp3");

				MediaPlayer fmpAudio = new MediaPlayer();
				fmpAudio.setDataSource(fisAudio.getFD());
				fmpAudio.prepare();
				fmpAudio.start();

			} catch (IOException ioe) {
				Log.e("START PLAYING", ioe.getMessage());
			}
		}
	}
}
